package writer;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Properties;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import javax.naming.InitialContext;

import utils.MessageUtils;

import news.News;
import news.NewsEvent;

public class WriterTopic implements javax.jms.MessageListener, Runnable {
	private TopicSession pubSession;
	private TopicSession subSession;
	private TopicPublisher publisher;
	private TopicConnection connection;
	private String username;
	private TopicSubscriber subscriber ;
	
	private HashMap<String, News> myNews ;
	private HashMap<String, Integer> myNewsRead ;
	
	/* Constructor. Establish JMS publisher and subscriber */
	public WriterTopic(String topicName, String username, String password) throws Exception {
		
		myNews = new HashMap<String, News>();
		myNewsRead = new HashMap<String, Integer>() ;
		this.username = username;
		// Obtain a JNDI connection
		Properties env = new Properties();
		// ... specify the JNDI properties specific to the vendor
		InitialContext jndi = new InitialContext(env);
		// Look up a JMS connection factory
		TopicConnectionFactory conFactory = (TopicConnectionFactory) jndi.lookup("NewsConnectionFactory");
		// Create a JMS connection
		connection = conFactory.createTopicConnection(username,password);
		connection.setClientID(java.util.UUID.randomUUID().toString());
		
		// Create two JMS session objects
		pubSession = connection.createTopicSession(false,Session.AUTO_ACKNOWLEDGE);
		subSession = connection.createTopicSession(false,Session.AUTO_ACKNOWLEDGE);
		// Look up a JMS topic
		Topic chatTopic = (Topic) jndi.lookup(topicName);
		// Create a JMS publisher and subscriber
		publisher = pubSession.createPublisher(chatTopic);
		
		String selector = "author = '"+username+"'";
		
		subscriber = subSession.createDurableSubscriber((Topic) jndi.lookup("NewsReadTopic"), "NewsReadTopic", selector, true);		
		// Set a JMS message listener
		subscriber.setMessageListener(this);
		// Intialize the Chat application
		
		// Start the JMS connection; allows messages to be delivered
		connection.start();
	}

	

	
	/* Create and send message using topic publisher */
	public void writeMessage(News news, String event) throws JMSException {
		
		TextMessage message = pubSession.createTextMessage();
		
		//String event = msg.getStringProperty(MessageUtils.NEWS_EVENT);
		String title = news.getTitle() ;
		String author = news.getAuthor();
		long datePublished = news.getDatePublished();
		long dateModified = news.getDateModified();
		String subDomain = news.getSubDomain();
		String content = news.getContent() ; 
		
		
		message.setStringProperty(MessageUtils.TITLE, title );
		message.setStringProperty(MessageUtils.AUTHOR, author );
		message.setLongProperty(MessageUtils.DATE_PUBLISHED, datePublished);
		message.setLongProperty(MessageUtils.DATE_MODIFIED, dateModified );
		message.setStringProperty(MessageUtils.SUBDOMAIN, subDomain );
		message.setStringProperty(MessageUtils.NEWS_EVENT, event);
		message.setText( content);
		
		myNews.put(title, news);
		myNewsRead.put(title, 0);
		
		publisher.publish(message);
		
		if(event.equals(NewsEvent.NEWS_DELETED)){
				
			myNews.remove(title);
			
			//mentin contoarele pentru titlurile publicate
			//myNewsRead.remove(title);
			
		}
		
	}

	/* Close the JMS connection */
	public void close() throws JMSException {
		connection.close();
	}

	@Override
	public void onMessage(Message msg) {
		// TODO Auto-generated method stub
		
		try {
			String event = msg.getStringProperty(MessageUtils.NEWS_EVENT);
			String title = msg.getStringProperty(MessageUtils.TITLE);
						
			
			 
			if(event.equals(NewsEvent.NEWS_READ)){
				Integer var = myNewsRead.get(title) ;
				int count = 0 ;
				if( var != null ){
					count = var.intValue() ;
					count += 1 ;
					myNewsRead.put(title, count);
				} else {
					System.err.println("News: (" + title + ") no longer exists!");
				}
				
				System.out.println("### Writer: " +  username + " news (" + title + ") read "+ count);
			}
			
	
		} catch (JMSException e) {
			e.printStackTrace();
		}
		
	}

	@Override
	public void run() {
		while (true) ;

	}

}